package cn.tellsea.service.impl;

import cn.tellsea.entity.AjaxResult;
import cn.tellsea.entity.BizAccount;
import cn.tellsea.mapper.BizAccountMapper;
import cn.tellsea.service.IBizAccountService;
import cn.tellsea.utils.BigDecimalUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 账户表 服务实现类
 * </p>
 *
 * @author Tellsea
 * @since 2021-12-31
 */
@Slf4j
@Service
public class BizAccountServiceImpl extends ServiceImpl<BizAccountMapper, BizAccount> implements IBizAccountService {

    @Override
    public AjaxResult decrease(Long userId, BigDecimal money) {
        log.info("------->扣减余额开始");
        //模拟超时异常，全局事务回滚
        //暂停几秒钟线程
        /*try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        BizAccount account = baseMapper.selectById(userId);
        account.setResidue(BigDecimalUtils.subtract(account.getResidue(), money));
        account.setUsed(BigDecimalUtils.add(account.getUsed(), money));
        baseMapper.updateById(account);
        log.info("------->扣减余额结束");
        return AjaxResult.success("扣减余额成功");
    }
}
